package com.zisuyi.game.sdk.game

import android.content.pm.PackageManager
import androidx.core.content.pm.PackageInfoCompat
import com.orhanobut.logger.Logger
import com.weilele.mvvm.MvvmConf
import com.weilele.mvvm.app
import com.weilele.mvvm.gson
import com.weilele.mvvm.utils.getAppKeyHash
import com.zisuyi.game.sdk.GameApp
import com.zisuyi.game.sdk.game.bean.AndroidJsBean

class GameReceiveMessage(private val gameEgret: GameEgret) {
    private val vibratorHelper by lazy { VibratorHelper() }

    /**
     * 处理从游戏端传过来的消息
     */
    fun distributeMessages(msg: String?) {
        msg ?: return
        if (MvvmConf.IS_DEBUG) {
            Logger.v("-----------------Js发送消息给原生----------------->")
            Logger.json(msg)
        }
        val bean = gson.fromJson(msg, AndroidJsBean::class.java)
        when (bean.type) {
            TYPE_HTTP_API -> {
                gameEgret.netRequest(bean)
            }
            TYPE_SHOW_VIDEO_AD -> {
                gameEgret.showGameVideoAd(bean)
            }
            TYPE_VIBRATE -> {
                vibratorHelper.vibrator()
                distributeMessages(bean)
            }
            TYPE_GET_TOKEN -> {//需要请求头信息
                gameEgret.sendToJs(
                    AndroidJsBean.success(
                        bean.type, gson.toJson(
                            linkedMapOf<String, String>(
                                "Version" to PackageInfoCompat.getLongVersionCode(info).toString(),
                                "Name" to packageName,
                                "Hash" to hash,
                                "Authorization" to "Bearer " + (GameApp.secret ?: "")
                            )
                        )
                    )
                )
            }
            else -> {
                distributeMessages(bean)
            }
        }
    }

    private fun distributeMessages(bean: AndroidJsBean) {
        distributeMessagesListeners.toList().forEach {
            it.invoke(bean, gameEgret)
        }
    }


    internal fun onCreate() {
        distributeMessagesListeners.toList().forEach {
            //发送对象的创建消息
            it.invoke(AndroidJsBean().apply {
                type = ON_CREATE
            }, gameEgret)
        }
    }

    internal fun onDestroy() {
        distributeMessagesListeners.toList().forEach {
            //发送对象的创建消息
            it.invoke(AndroidJsBean().apply {
                type = ON_DESTROY
            }, gameEgret)
        }
    }

    companion object {

        /**
         * 获取包的签名
         */
        val hash by lazy {
            val hashs = app.getAppKeyHash()
            var hashValue = "null"
            if (hashs.isNotEmpty()) {
                hashValue = hashs[0]
            }
            hashValue.trimEnd('\n')
        }
        val packageName by lazy { app.packageName }

        val info by lazy {
            app.packageManager.getPackageInfo(
                packageName,
                PackageManager.GET_ACTIVITIES
            )
        }

        private val distributeMessagesListeners =
            mutableListOf<Function2<AndroidJsBean, GameEgret, Unit>>()

        fun addDistributeMessagesListener(
            listener: Function2<@ParameterName("message") AndroidJsBean,
                    @ParameterName("egret") GameEgret, Unit>
        ) {
            if (!distributeMessagesListeners.contains(listener)) {
                distributeMessagesListeners.add(listener)
            }
        }

        fun removeDistributeMessagesListener(
            listener: Function2<@ParameterName("message") AndroidJsBean,
                    @ParameterName("egret") GameEgret, Unit>
        ) {
            distributeMessagesListeners.remove(listener)
        }

        //-------------------------------TYPE---------------------------

        // android → h5
        //邀请
        const val EGRET_INVITATION = "egret_invitation"

        //金币或者钻石变化
        const val TYPE_USER_GAME_INFO = "TYPE_USER_GAME_INFO"

        //video
        const val EGRET_ADS_VIDEO = "egret_ads_video"

        //对象创建
        const val ON_CREATE = "ON_CREATE"

        const val TYPE_GET_TOKEN = "TYPE_GET_TOKEN"

        //对象销魂
        const val ON_DESTROY = "ON_DESTROY"

        //显示设置对话框
        const val TYPE_SHOW_SETTING_DIALOG = "TYPE_SHOW_SETTING_DIALOG"

        //展示视频广告
        const val TYPE_SHOW_VIDEO_AD = "native_google_video"
        const val TYPE_VIBRATE = "TYPE_SHOCK"
        const val TYPE_CLICK_RIGHT = "TYPE_CLICK_RIGHT"
        const val VIDEO_SUCCESS = "watch_video_success"; //看视频成功
        const val VIDEO_FAIL = "watch_video_fail";  //看视频失败

        //http请求
        const val TYPE_HTTP_API = "TYPE_HTTP_API"

        //资产发生变化
        const val TYPE_ASSETS_CHANGE = "TYPE_ASSETS_CHANGE"

        //游戏加载完毕
        const val TYPE_GAME_LOAD_FINISH = "TYPE_GAME_LOAD_FINISH"

        //点击按钮，需要播放声音
        const val TYPE_CLICK_BUTTON_SOUND = "TYPE_CLICK_BUTTON_SOUND"

        //打开兑换按钮
        const val TYPE_OPEN_REDEEM_PAGE = "TYPE_OPEN_REDEEM_PAGE"
        //打开兑换按钮
        const val TYPE_OPEN_SPIN_PAGE = "TYPE_SPIN_LOTTERY"

        //退出游戏
        const val TYPE_GAME_DESTROY = "TYPE_GAME_DESTROY"

        //--------------------------CODE--------------------------
        //视频广告展示失败
        const val ERROR_CODE_SHOW_VIDEO_AD = -1

        //http 请求失败
        const val ERROR_CODE_HTTP_ERROR = -2
    }
}